import { message } from '@/utils/message'
import type { PaginationProps } from '@pureadmin/table'
import { ElMessageBox } from 'element-plus'

import { formatDate } from '@/utils/common'
import { downloadFile } from '@/utils/http'
import { useToggle } from '@vueuse/core'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { delTable, downLoadCode, genCode, listTable, previewTable, synchDb } from './api'

export function useDict() {
  const router = useRouter()
  const route = useRoute()
  const queryParams = reactive({
    tableName: '',
    tableComment: '',
    dateRange: null,
  })
  const preview = reactive({
    title: '代码预览',
    data: {},
    activeName: 'domain.java',
  })
  const dataList = ref([])
  const loading = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const tableNames = ref([])

  const [showPreviewDialog, toggleShowPreviewDialog] = useToggle()

  const [showImportTableDialog, toggleShowImportTableDialog] = useToggle()

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  })
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: 55,
      align: 'left',
    },
    {
      label: '序号',
      type: 'index',
      width: 70,
    },
    {
      label: '表名称',
      prop: 'tableName',
      width: 150,
    },
    {
      label: '表描述',
      prop: 'tableComment',
      width: 150,
    },
    {
      label: '实体',
      prop: 'className',
      width: 150,
    },
    {
      label: '创建时间',
      width: 180,
      prop: 'createTime',
      formatter: ({ createTime }) => formatDate(createTime),
    },
    {
      label: '更新时间',
      width: 180,
      prop: 'updateTime',
      formatter: ({ createTime }) => formatDate(createTime),
    },
    {
      label: '操作',
      fixed: 'right',
      width: 300,
      slot: 'operation',
    },
  ]

  /** 生成代码操作 */
  async function handleGenTable(row) {
    const tbNames = row.tableName || tableNames.value
    if (!tbNames || tbNames.length === 0) {
      return message('请选择要生成的数据', { type: 'error' })
    }

    if (row.genType === '1') {
      await genCode(row.tableName)
      return message(`成功生成到自定义路径：${row.genPath}`, {
        type: 'success',
      })
    } else {
      await downLoadCode(tbNames, 'code.zip')
    }
  }

  /** 同步数据库操作 */
  function handleSynchDb(row) {
    const tableName = row.tableName
    ElMessageBox.confirm('确认要强制同步"' + tableName + '"表结构吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(function () {
        return synchDb(tableName)
      })
      .then(() => {
        message('同步成功', { type: 'success' })
      })
      .catch(() => {})
  }

  /** 预览按钮 */
  function handlePreview(row) {
    previewTable(row.tableId).then((response) => {
      preview.data = response.data
      console.log(preview.data)

      toggleShowPreviewDialog(true)
      preview.activeName = 'domain.java'
    })
  }

  /** 导出按钮操作 */
  function handleExport() {
    downloadFile(
      'system/post/export',
      {
        ...queryParams,
      },
      `岗位管理.xlsx`
    )
  }

  /** 改变分页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  /** 改变当前分页 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.tableId)
    tableNames.value = selection.map((item) => item.tableName)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 修改按钮操作 */
  function handleEditTable(row) {
    const tableId = row.tableId || ids.value[0]
    router.push({
      path: '/tool/gen-edit/' + tableId,
      query: { pageNum: pagination.currentPage },
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const tableIds = row.tableId || ids.value
    ElMessageBox.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(function () {
        return delTable(tableIds)
      })
      .then(() => {
        message('删除成功', { type: 'success' })
        onSearch()
      })
      .catch(() => {})
  }

  /** 复制代码成功 */
  function copyTextSuccess() {
    message('复制成功', { type: 'success' })
  }

  async function onSearch() {
    loading.value = true
    const params = {
      ...queryParams,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
    const { rows, total } = await listTable(params)
    dataList.value = rows
    pagination.total = total
    loading.value = false
  }

  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    onSearch()
  }

  onMounted(() => {
    const { pageNum } = route.query
    if (pageNum) {
      pagination.currentPage = Number(pageNum)
    }
    onSearch()
  })

  return {
    preview,
    loading,
    columns,
    multiple,
    dataList,
    pagination,
    queryParams,
    showPreviewDialog,
    showImportTableDialog,
    toggleShowImportTableDialog,
    toggleShowPreviewDialog,
    onSearch,
    resetForm,
    copyTextSuccess,
    handlePreview,
    handleGenTable,
    handleSynchDb,
    handleEditTable,
    handleDelete,
    handleExport,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
  }
}
